package dao

import (
	"github.com/astaxie/beego/orm"
	"xiaoercaidan/publicResources/models"
	"errors"
	"github.com/astaxie/beego/validation"
	"log"
	"fmt"
)

func InserShop(shop *models.Shop) (error) {

	o := orm.NewOrm()

	_, err := o.Insert(shop)

	if err == nil {
		return nil
	} else {
		return err
	}

}

func QeryShopBlur(params map[string]string) (*[]models.Shop) {

	o := orm.NewOrm()

	var shops []models.Shop

	var qs orm.QuerySeter

	qs = o.QueryTable("shop")

	for k, v := range params {

		if k == "user_id" || k == "code" || k == "id" {
			qs = qs.Filter(k + "__exact", v)
		} else {
			qs = qs.Filter(k + "__icontains", v)
		}

	}

	qs.All(&shops)

	fmt.Println(shops)

	return &shops

}

func QeryShopDetail(shopId string) (models.Shop) {

	o := orm.NewOrm()

	var shops models.Shop

	var qs orm.QuerySeter

	qs = o.QueryTable("shop")

	qs = qs.Filter("id__exact", shopId)

	qs.One(&shops)

	return shops

}

func QeryShop(params map[string]string) (*[]models.Shop) {

	o := orm.NewOrm()

	var shops []models.Shop

	var qs orm.QuerySeter

	qs = o.QueryTable("shop")

	for k, v := range params {
		qs = qs.Filter(k + "__exact", v)
	}

	qs.All(&shops)

	if (len(shops) > 0) {
		return &shops
	} else {
		return nil
	}

}

func DeleteShop(ids string) (error) {

	o := orm.NewOrm()

	_, err := o.Raw("delete from shop where id in(" + ids + ")").Exec()

	if err == nil {
		return nil
	} else {
		return err
	}
}

func checkShop(u *models.Shop) (err error) {
	valid := validation.Validation{}
	b, _ := valid.Valid(&u)
	if !b {
		for _, err := range valid.Errors {
			log.Println(err.Key, err.Message)
			return errors.New(err.Message)
		}
	}
	return nil
}

func UpdateShop(shop *models.Shop) (error) {

	o := orm.NewOrm()

	_, err := o.QueryTable("shop").Filter("id", shop.Id).Update(orm.Params{
		"shop_name": shop.ShopName,
		"tel": shop.Tel,
		"address": shop.Address,
		"user_id": shop.UserId,
	})

	return err

}
